import java.util.*;

class Solution {
    int m;
    int n;

    public int[][] updateMatrix(int[][] mat) {
        m = mat.length;
        n = mat[0].length;
        int[][] distance = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (mat[i][j] == 1) {
                    int step = bfs(mat, i, j);
                    distance[i][j] = step;
                } else {
                    distance[i][j] = 0;
                }
            }
        }
        return distance;
    }

    int[] dx = {1,-1,0,0};
    int[] dy = {0,0,1,-1};
    boolean[][] visited;

    private int bfs(int[][] mat, int i, int j) {
        Queue<int[]> queue = new LinkedList<>();
        visited = new boolean[m][n];
        queue.offer(new int[]{i, j});
        visited[i][j] = true;
        int step = 0;
        while (!queue.isEmpty()) {
            step++;
            int size = queue.size();
            while (size-- != 0) {
                int[] arr = queue.poll();
                for (int k = 0; k < 4; k++) {
                    int sr = arr[0] + dx[k], sc = arr[1] + dy[k];
                    if (sr >= 0 && sr < m && sc >= 0 && sc < n && !visited[sr][sc]) {
                        if (mat[sr][sc] == 0) {
                            return step;
                        }
                        queue.offer(new int[]{sr, sc});
                        visited[sr][sc] = true;
                    }
                }
            }
        }
        return -1;
    }
}